package com.miyake.loveviewweb.server.controller;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Key;
import com.miyake.loveviewweb.shared.model.BinaryModel;
import com.miyake.loveviewweb.shared.model.DataModel;

public class DownloadController extends Controller {

    @Override
    public Navigation run() throws Exception {
        if (isGet()) {
            Key key = Datastore.stringToKey(this.request.getParameter("key"));
            DataModel dataModel = Datastore.get(DataModel.class, key);
            BinaryModel bin = Datastore.get(BinaryModel.class, dataModel.getOriginalData());
            response.setContentType("application/octet-stream");
            //for (byte b : bin.getBlobData().getBytes()) {
            //    this.response.getOutputStream().print(b);
            //}
            this.response.getWriter().print(new String(bin.getBlobData().getBytes()));
            this.response.setHeader(
                "Content-Disposition",
                "filename=\"" + dataModel.getName() + "\"");

            //this.response.getWriter().print(bin.getBlobData());
            this.response.flushBuffer();
            
        }
        return null;//forward("download.jsp");
    }
}
